package com.neelsys.visualisation.service.adapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.neelsys.visualisation.domain.BaseNodeEntity;
import com.neelsys.visualisation.domain.MajorCombination;

public class NextLevelCourseAdapter {

	private long level;

	private MajorCombAdapter combAdapter;

	public NextLevelCourseAdapter(MajorCombAdapter combAdapter, long level) {
		this.combAdapter = combAdapter;
		this.level = level;
	}

	public void adapt(Set<MajorCombination> majorCombs,
			BaseNodeEntity fromNode) {

		Set<MajorCombination> nxtLevelDirCourses = retainDistinctCourseIds(majorCombs);

		for (MajorCombination majorCombination : nxtLevelDirCourses) {

			combAdapter.addNodeToGraph(combAdapter.jsonGraph, combAdapter
					.createNewNode(majorCombination.getCourseIdentifier(), "D",
							majorCombination.getNodeId(), level));
			combAdapter.createRelationShip(fromNode, majorCombination,
					combAdapter.jsonGraph);
			
			NextLevelsAdapter nextLevelsAdapter=new NextLevelsAdapter(combAdapter, level);
			nextLevelsAdapter.adapt(majorCombination);

		}

	}

	private Set<MajorCombination> retainDistinctCourseIds(
			Set<MajorCombination> majorCombinationSet) {

		Set<MajorCombination> tmpSet = new HashSet<MajorCombination>();

		Iterator<MajorCombination> setIt = majorCombinationSet.iterator();

		List<String> courseIdList = new ArrayList<String>();

		while (setIt.hasNext()) {
			MajorCombination comb = setIt.next();
			if (!courseIdList.contains(comb.getCourseIdentifier())) {
				courseIdList.add(comb.getCourseIdentifier());
				tmpSet.add(comb);
			}
		}

		return tmpSet;
	}
}
